package com.kdtech.analyse.blog;
import com.kdtech.crawler.CrawlHTML;

import org.apache.commons.lang.StringUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;


import com.kdtech.entity.crawler.UrlMeta;
import com.kdtech.entity.data.NewsMeta;
import com.kdtech.utils.DateUtils;
import com.kdtech.utils.HtmlCleaner;
import com.kdtech.analyse.AnalyseNews;

public class SinaBlogAnalyse implements AnalyseNews{

	//http://blog.sina.com.cn/s/blog_4fcb878a0102ekbp.html?tj=1
//	/http://blog.sina.com.cn/s/blog_4d1b21fc01019uis.html?tj=1
	//http://blog.sina.com.cn/u/a2f1ac720101ex3d
	
	public boolean isDetailPage(String url) {
		boolean bRet = false;
		String[] regex = {
				"http://.*blog.sina.com.cn/s/blog_[0-9a-z]*.html\\?tj=[0-9]*"
				,"http://blog.sina.com.cn/s/blog_.*"
				,"http://blog.sina.com.cn/u/[a-z0-9]{16}"
				};
		for (int i = 0; i < regex.length; i++) {
			if (url.matches(regex[i])) {
				return true;
			}
		}
		return bRet;
	}

	
	public NewsMeta parserHtml(UrlMeta urlMeta) {
		String url = urlMeta.getUrl();
		if(url.indexOf("?tj=")!=-1){
			url=url.substring(0,url.indexOf("?"));
		}
		urlMeta = CrawlHTML.responseToURL(url);
		String html = urlMeta.getHtml();
		if (html== null) {
		}
		NewsMeta blog = new NewsMeta();
		blog.setUrl(url);
		String title = null;
		String content = null;
		Long date = null;
		String author = null;
		Document doc = Jsoup.parse(html);
		title  = doc.select("div.articalTitle h2.titName").text().trim();
		date = DateUtils.matchDate(doc.select("div.articalTitle span.time").text());
		if(date==null){
			date = DateUtils.matchDate(doc.select("div.articalTitle").text());
		}
		doc.select("div.articalContent font[color=#FFFFFF]").remove();
		doc.select("div.articalContent a").remove();
		content = HtmlCleaner.getContentHtml(url,  doc.select("div.articalContent"));
		if(StringUtils.isBlank(title)){
			title  = doc.select("div.sinabloga h1").text();
		}
		if(date==null){
			date = DateUtils.matchDate(doc.select("div.sinabloga div.artinfo span.time").text());
		}
		if(StringUtils.isBlank(title)){
		}
		author = doc.select("strong#ownernick").text();

		blog.setAuthor(author);
		blog.setTitle(title);
		blog.setContent(content);
		blog.setDate(date);
		blog.setUpdateUrl(url);
		return blog;
	}



	public static void main(String[] args) {
		String url = "http://blog.sina.com.cn/s/blog_53a2e03d0101g51q.html?tj=1";
		SinaBlogAnalyse test = new SinaBlogAnalyse();
		if(test.isDetailPage(url)){
			UrlMeta responseToURL = CrawlHTML.responseToURL(url);
			NewsMeta parserHtml = test.parserHtml(responseToURL);
			System.out.println(parserHtml);
//			System.out.println(test.Update(parserHtml));
		}else{
			System.out.println("不符合规则");
		}
	}
	

	
	public NewsMeta Update(NewsMeta meta) {
		return null;
	}
}
